package com.meiyu.live.ui.main;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.auth.AuthService;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.BaseApplication;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.eventbus.LoginEvent;
import com.meiyu.live.net.param.BaseBodyParams;
import com.meiyu.live.net.param.PersonalParams;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.net.response.PersonalResponse;
import com.meiyu.live.net.response.StringRemarkResponse;
import com.meiyu.live.tv.anchor.StartPlayActivity;
import com.meiyu.live.tv.audience.AudienceActivity;
import com.meiyu.live.ui.login.LoginActivity;
import com.meiyu.live.ui.mine.MineFragment;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.NetLoadingDailog;
import com.meiyu.live.widget.VinDialog;

import de.greenrobot.event.EventBus;

public class MainActivity extends BaseActivity implements Listener<BaseResponse>, View.OnClickListener {

    private FrameLayout layout_container;
    private NetLoadingDailog dialog_loading;
    private ImageView btn_tab_home, btn_tab_startlive, btn_tab_mine, tab_startlive_cover;
    private View layout_dialog;

    private HomeFragment homeFragment;
    private MineFragment mineFragment;
    private Fragment currentFragment;
    public static final String HOOK_STATUS = "hook_status";
    int hook_status = 1;
    boolean isShowed = false;

    /**
     * 开启直播状态，-1 还没有获取到数据,0 还未申请，1 已经申请还不能开播，2 可以立即开播
     */
    private int liveStatus = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initView();
        initAnimator();
        initData();
        showGuidance();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getLiveStatusData();

        if (UserConfig.getInstance().getParams() != null) {
            AudienceActivity.start(this, UserConfig.getInstance().getParams());
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void initView() {
        dialog_loading = new NetLoadingDailog(this);

        layout_container = (FrameLayout) findViewById(R.id.layout_container);
        btn_tab_home = (ImageView) findViewById(R.id.tab_home);
        btn_tab_home.setOnClickListener(this);
        btn_tab_startlive = (ImageView) findViewById(R.id.tab_startlive);
        btn_tab_startlive.setOnClickListener(this);
        tab_startlive_cover = (ImageView) findViewById(R.id.tab_startlive_cover);
        btn_tab_mine = (ImageView) findViewById(R.id.tab_mine);
        btn_tab_mine.setOnClickListener(this);

        homeFragment = HomeFragment.newInstance();
        mineFragment = MineFragment.newInstance();
        translateFragment(homeFragment);
    }

    private void initData() {
        getData();
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {

    }

    private void getData() {

        if (!isShowed) {
            request(new BaseBodyParams(Constant.VERSION + Constant.UrlParams.VIN), StringRemarkResponse.class, new Response.Listener<StringRemarkResponse>() {
                @Override
                public void onResponse(StringRemarkResponse vinResponse) {
                    if (vinResponse.getStatusCode() == 6) {
                        VinDialog vinDialog = new VinDialog(MainActivity.this, vinResponse.getMsg(), vinResponse.getRemark());
                        vinDialog.setCancelable(false);
                        vinDialog.show();
                        isShowed = true;
                    }
                }
            });
        }

        if (UserConfig.getInstance().isLogin()) {
            dialog_loading.loading();
            BaseApplication.getApp().doIMLogin();
            request(new PersonalParams(null), PersonalResponse.class, new Response.Listener<PersonalResponse>() {
                @Override
                public void onResponse(PersonalResponse personalResponse) {
                    dialog_loading.dismissDialog();
                    if (personalResponse != null) {
                        UserConfig.getInstance().setPersonalInfo(personalResponse.getPrivateInfo());
                        UserConfig.getInstance().setRelationInfo(personalResponse.getRelationinfo());
                        UserConfig.getInstance().setActiveInfos(personalResponse.getActiveInfo());
                    }
                }
            });
        }
    }


    @Override
    public void onError() {
        dialog_loading.dismissDialog();
        super.onError();
    }

    @Override
    public void onClick(View view) {
        if (view == btn_tab_home) {
            translateFragment(homeFragment);
        } else if (view == btn_tab_startlive) {
            if (!UserConfig.getInstance().isLogin()) {
                startActivity(LoginActivity.class);
            } else if (liveStatus == 2) {
                startActivity(StartPlayActivity.class);
            } else {
                if (UserConfig.getInstance().isLogin()) {
                    dialog_loading.loading();
                    BaseBodyParams b = new BaseBodyParams();
                    b.setUrl(Constant.VERSION + Constant.UrlParams.ANCHORVALIDATE);
                    request(b, BaseResponse.class, new Response.Listener<BaseResponse>() {
                        @Override
                        public void onResponse(BaseResponse onlyStatusResponse) {
                            dialog_loading.dismissDialog();
                            if (onlyStatusResponse == null) {
                                Log.e("MainAcitivity", "ANCHORVALIDATE-null");
                            } else if (onlyStatusResponse.getStatusCode() == 2) {
                                ToastUtil.show(onlyStatusResponse.getMsg());
                            } else {
                                if (onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
                                    hook_status = 0;
                                }
                                Intent intent = new Intent(MainActivity.this, ChooseLiveActivity.class);
//        intent.putExtra(MEDIA_PATH, "rtmp://p5886108b.live.126.net/live/15853282a0654e1788a127c7ecf374fd?wsSecret=9729a51c63c6a79ee949ec7412a5ab5c&wsTime=1468391369");
                                intent.putExtra(HOOK_STATUS, hook_status);
                                startActivity(intent);
                            }

                        }
                    });
                }

//                showStartLiveDialog(!isDialogShow);
            }
        } else if (view == btn_tab_mine) {
            translateFragment(mineFragment);
        }
//        else if (view == btn_apply) {
//            showStartLiveDialog(false);
//            dialog_loading.loading();
//            BaseBodyParams b = new BaseBodyParams();
//            b.setUrl(Constant.VERSION + Constant.UrlParams.ANCHORVALIDATE);
//            request(b, OnlyStatusResponse.class, new Listener<OnlyStatusResponse>() {
//                @Override
//                public void onResponse(OnlyStatusResponse onlyStatusResponse) {
//                    dialog_loading.dismissDialog();
//                    if (onlyStatusResponse != null && onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
//                        startActivity(Apply1Activity.class);
//                    } else {
//                        ToastUtil.show("已申请过，请等到约定时间开播");
//                    }
//                }
//            });
//        } else if (view == btn_live) {
//            showStartLiveDialog(false);
//            dialog_loading.loading();
//            BaseBodyParams b = new BaseBodyParams(UserConfig.getInstance().getSession_token());
//            b.setUrl(Constant.VERSION + Constant.UrlParams.CHECK_PERMISSIONS);
//            request(b, OnlyStatusResponse.class, new Listener<OnlyStatusResponse>() {
//                @Override
//                public void onResponse(OnlyStatusResponse onlyStatusResponse) {
//                    dialog_loading.dismissDialog();
//                    if (onlyStatusResponse != null && onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
//                        startActivity(StartPlayActivity.class);
//                    } else {
//                        ToastUtil.show("还不可以开启直播哦");
//                    }
//                }
//            });
//        }
    }

    private void translateFragment(Fragment fragment) {
        if (currentFragment == fragment) {
            return;
        }
        if (fragment instanceof HomeFragment) {
            btn_tab_home.setImageResource(R.drawable.main_tab_home_s);
            btn_tab_mine.setImageResource(R.drawable.main_tab_mine_n);
        } else if (fragment instanceof MineFragment) {
            btn_tab_home.setImageResource(R.drawable.main_tab_home_n);
            btn_tab_mine.setImageResource(R.drawable.main_tab_mine_s);
        }
        currentFragment = fragment;
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.layout_container, fragment);
        transaction.commit();
    }

    private void getLiveStatusData() {
        if (!UserConfig.getInstance().isLogin()) {
            return;
        }
        BaseBodyParams b = new BaseBodyParams();
        b.setUrl(Constant.VERSION + Constant.UrlParams.CHECK_PERMISSIONS);
        request(b, BaseResponse.class, new Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse onlyStatusResponse) {
                if (onlyStatusResponse != null) {
                    if (onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
                        liveStatus = 2;
                        showStartAnimation(true);
                    } else if (onlyStatusResponse.getStatusCode() == 2) {
                        liveStatus = 0;
                        showStartAnimation(false);
                    } else {
                        liveStatus = 0;
                        showStartAnimation(false);
                    }
                } else {
                    showStartAnimation(false);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }

    private AlphaAnimation animation_startlive;

    private void initAnimator() {
        final int ANIMATION_DURATION = 1000;
        animation_startlive = new AlphaAnimation(0f, 1f);
        animation_startlive.setRepeatMode(ValueAnimator.REVERSE);
        animation_startlive.setRepeatCount(ValueAnimator.INFINITE);
        animation_startlive.setDuration(ANIMATION_DURATION);
        animation_startlive.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                tab_startlive_cover.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                tab_startlive_cover.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void showStartAnimation(boolean isShow) {
        if (isShow) {
            tab_startlive_cover.clearAnimation();
            tab_startlive_cover.startAnimation(animation_startlive);
        } else {
            tab_startlive_cover.clearAnimation();
        }
    }

    private void showGuidance() {
        int savedVersionCode = UserConfig.getInstance().getGuidanceShowVersion();

        PackageManager packageManager = getPackageManager();
        PackageInfo packageInfo;
        int currentVersionCode = 0;
        try {
            packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            currentVersionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (savedVersionCode != currentVersionCode) {
            UserConfig.getInstance().setGuidanceShowVersion(currentVersionCode);
            startActivity(GuidanceActivity.class);
        }
    }

    public void onEvent(LoginEvent event) {
        if (event.isLogin) {
            if (UserConfig.getInstance().getParams() != null) {
                AudienceActivity.start(this, UserConfig.getInstance().getParams());
            }
            getData();
            BaseApplication.getApp().doIMLogin();
        } else {
            NIMClient.getService(AuthService.class).logout();
        }
    }
}
